<?php

namespace App\Http\Controllers\API\Activity;

use Illuminate\Http\Request;
use App\Http\Controllers\API\APIController;

use Validator;
use App\Models\API\Notification;
use App\Models\API\Activity;
use App\Models\API\User;
use DB;

class JoinController extends APIController
{
    public function index($id)
    {
        $users = \App\Models\API\ActivityJoin::where('activity_id', $id)
            ->join('users', 'activity_joins.user_id', '=', 'users.id')
            ->select('activity_joins.*', 'users.user_name', 'users.user_img')
            ->get();
        return response()->json($this->setJson(true, $users), 200);
    }

    public function join(Request $request, $id)
    {
    	$v = Validator::make($request->all(), [
            'user_id'   => 'required',
            'companion_id' => 'required'
        ]);

        if ($v->fails())
        {
        	return response()->json($this->setJson(false, $v->errors()), 422);
        }

		if ($v->passes())
		{
            $applyUser = User::find($request->get('companion_id'));
            $activity = Activity::find($id);

			$userInfo = $request->only(['user_id', 'companion_id']);
			$res = $activity->joinUser($userInfo);

            $detail = [
                'activity_id' => $activity->id,
                'title'       => $activity->title,
                'user_id'     => $applyUser->id,
                'user_name'   => $applyUser->user_name,
                'user_img'    => $applyUser->user_img,
                'sign'        => '申请加入你的活动，是否同意？',
                'is_joined'   => 0,
            ];

            $notification = Notification::where([
                ['user_id', $activity->user_id],
                ['type', 'new_activity_apply'],
                ['detail', json_encode($detail)],
            ])->first();

            $detail['is_joined'] = 1;
            $notification->detail = json_encode($detail);
            $notification->save();
            
			return response()->json($this->setJson(true, $res), 200);
		}
    }

    public function cancel(Request $request, $id)
    {
        $v = Validator::make($request->all(), [
            'user_id'   => 'required'
        ]);

        if ($v->fails())
        {
            return response()->json($this->setJson(false, $v->errors()), 422);
        }

        if ($v->passes())
        {
            $userInfo = $request->only('user_id');
            $res = Activity::find($id)->cancelJoin($userInfo);
            return response()->json($this->setJson(true, $res), 200);
        }
    }
    
    private function setJson($status, $msg)
    {
        $res = [
            'status' => $status,
            'msg'    => $msg
        ];
        return $res;
    }
}
